package com.daxia.ogmall.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daxia.ogmall.dao.SpaceObjectDAO;
import com.daxia.ogmall.model.SpaceObject;
import com.daxia.ogmall.dto.SpaceObjectDTO;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.BeanMapper;

@Service
public class SpaceObjectService {
	
	@Autowired
	private SpaceObjectDAO spaceObjectDAO;
	
	public List<SpaceObjectDTO> find(SpaceObjectDTO query, Page page) {
		List<SpaceObject> models = spaceObjectDAO.find(query, page);
		List<SpaceObjectDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<SpaceObjectDTO> findAll() {
		return this.find(new SpaceObjectDTO(), null);
	}
	
	public List<SpaceObjectDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new SpaceObjectDTO(), page);
	}
	
	public Long create(SpaceObjectDTO dto) {
		SpaceObject model = new SpaceObject();
		toModel(model, dto);
		return spaceObjectDAO.create(model);
	}
	
	public SpaceObjectDTO load(Long id) {
	    SpaceObject model = spaceObjectDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(SpaceObjectDTO dto) {
		SpaceObject model = spaceObjectDAO.load(dto.getId());
		toModel(model, dto);
		spaceObjectDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				throw new RuntimeException("未实现删除逻辑，请确认是物理删除还是逻辑删除");
				// spaceObjectDAO.deleteById(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public SpaceObjectDTO findOne(SpaceObjectDTO query) {
		SpaceObject model = spaceObjectDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<SpaceObjectDTO> toDTOs(List<SpaceObject> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<SpaceObjectDTO>(0);
		}
		List<SpaceObjectDTO> dtos = new ArrayList<SpaceObjectDTO>(models.size());
		for (SpaceObject model : models) {
	        SpaceObjectDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private SpaceObjectDTO toDTO(SpaceObject model) {
		if (model == null) {
			return null;
		}
		SpaceObjectDTO dto = BeanMapper.map(model, SpaceObjectDTO.class);
		
		return dto;
	}
	
	private void toModel(SpaceObject model, SpaceObjectDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<SpaceObject> toModels(List<SpaceObjectDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<SpaceObject>(0);
		}
		List<SpaceObject> models = new ArrayList<SpaceObject>(dtos.size());
		for (SpaceObjectDTO dto : dtos) {
	        SpaceObject model = new SpaceObject();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
